<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<canvas id="c1" width="800" height="600" style="border: 1px solid;"></canvas>
		<br>
		<button id="boldBtn" type="button">加粗</button>
		<button id="thinBtn" type="button">减细</button>
		<input type="color" name="" id="color" value="" />
		<button type="button" id="saveBtn">保存签名</button>
		<!-- <a href="" id="download" download="签名">下载签名</a> -->
		<button id="clear" type="button">橡皮擦</button>
		<button id="nullBtn" type="button">清空画布</button>
		<script type="text/javascript">
			var canvas = document.querySelector('#c1')
			var ctx = canvas.getContext('2d')
			ctx.lineJoin = 'round'
			ctx.lineCap = 'round'
			
			// 设置是否允许绘制的标志
			var isDraw = false
			// 监听canvas鼠标按下事件
			canvas.onmousedown = function(event) {
				isDraw = true
				ctx.beginPath()
				var x = event.pageX - canvas.offsetLeft
				var y = event.pageY - canvas.offsetTop
				ctx.moveTo(x, y)
			}
			
			// 监听鼠标弹起事件
			canvas.onmouseup = function() {
				isDraw = false
				ctx.closePath()
			}
			
			// 监听鼠标离开事件
			canvas.onmouseleave = function() {
				isDraw = false
				ctx.closePath()
			}
			
			// 监听鼠标移动进行绘制
			canvas.onmousemove = function(event) {
				if(isDraw) {
					console.log(event)
					var x = event.pageX - canvas.offsetLeft
					var y = event.pageY - canvas.offsetTop
					ctx.lineTo(x, y)
					ctx.stroke()
				}
			}
			
			// 设置画笔的粗细
			var boldBtn = document.querySelector('#boldBtn')
			boldBtn.onclick = function() {
				ctx.globalCompositeOperation = 'source-over'
				ctx.lineWidth = 10
			}
			
			// 设置画笔的粗细
			var thinBtn = document.querySelector('#thinBtn')
			thinBtn.onclick = function() {
				ctx.globalCompositeOperation = 'source-over'
				ctx.lineWidth = 2
			}
			
			// 设置画笔的颜色
			var inputColor = document.querySelector('#color')
			inputColor.onchange = function(event) {
				console.log(event)
				console.log(inputColor.value)
				ctx.strokeStyle = inputColor.value
			}
			
			// 保存签名
			var saveBtn = document.querySelector('#saveBtn')
			saveBtn.onclick = function() {
				// 将图片转化成数据地址
				var urlData = canvas.toDataURL()
				var img = new Image()
				img.src = urlData
				document.body.appendChild(img)
				var download = document.createElement('a')
				download.setAttribute('download', '签名22')
				download.href = urlData
				download.click()
			}
			
			// 设置橡皮擦
			var clearBtn = document.querySelector('#clear')
			clearBtn.onclick = function() {
				ctx.globalCompositeOperation = 'destination-out'
				ctx.lineWidth = 30
			}
			
			// 清空画布
			var nullBtn = document.querySelector('#nullBtn')
			nullBtn.onclick = function() {
				ctx.clearRect(0,0,800,600)
			}
		</script>
	</body>
</html>
